<?php
class IndexController{
    private $data;
    public function __construct()
    {
        $this->data = include './data.php';
    }
    public function __call($name, $arguments)
    {
        success('别乱输,小样!','index.php');
    }

    /**
     * 文章首页
     */
    public function index(){
        $data = $this->data;
        include './View/index.html';
    }

    /**
     * 发布文章
     */
    public function add(){
        if(IS_POST){
            //发布时间
            $_POST['sendtime'] = time();
            $this->data[] = $_POST;
            file_put_contents('./data.php',"<?php return " . var_export($this->data,true) . " ?>");
            success('添加成功','index.php');
        }
        include './View/add.html';
    }

    /**
     * 编辑文章
     */
    public function edit(){
        $id = intval($_GET['id']);
        if(!$this->check($id)){
            success('该文章不存在','index.php');
        }else{
            //如果是提交就修改
            if(IS_POST){
                //先获得发布时间(修改的时候不能动发布时间)
                $sendTime = $this->data[$id]['sendtime'];
                $_POST['sendtime'] = $sendTime;
                //覆盖原数据
                $this->data[$id] = $_POST;
                file_put_contents('./data.php',"<?php return " . var_export($this->data,true) . " ?>");
                success('修改成功','index.php');

            }else{//否则显示模板和旧数据
                $data = $this->data[$id];
                include './View/edit.php';
            }
        }
    }

    /**
     * 删除
     */
    public function del(){
        $id = intval($_GET['id']);
        //如果用户乱改下标的时候,告诉他文章不存在
        if(!$this->check($id)){
            success('文章不存在','index.php');
        }
        //删除
        unset($this->data[$id]);
        file_put_contents('./data.php',"<?php return " . var_export($this->data,true) . " ?>");
        success('删除成功','index.php');
    }

    /**
     * 阅读文章
     */
    public function show(){
        $id = intval($_GET['id']);
        //如果用户乱改下标的时候,告诉他文章不存在
        if(!$this->check($id)){
            success('文章不存在','index.php');
        }
        $data = $this->data[$id];
        include './View/show.php';
    }

    /**
     * 检测文章是否存在
     * @param $id [要检测文章的下标]
     */
    private function check($id){
        if(!isset($this->data[$id])){
            return false;
        }
        return true;
    }
}







